<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html" ; charset="utf-8" />
    <title>宏宇教育信息采集</title>
    <link href="./index.css" rel="stylesheet" type="text/css" />
  </head>

  <style>
    /* .id-front .el-upload--picture-card, .id-back .el-upload--picture-card, .cun1 .el-upload--picture-card, .cun2 .el-upload--picture-card, .cun1 .el-upload--picture-card, .cun1 .el-upload--picture-card {
        display: none;
    } */
    .hide .el-upload--picture-card {
      display: none;
    }
    .box-card {
      margin: 20px 0;
    }
  </style>

  <body>
    <div id="app">
      <app-base-information
        :file-map="fileList"
        :type="type"
        ref="baseInfo"
        @on-get-info="getInfoByIdNoHandler"
      ></app-base-information>
      <!-- 在没有学历数据的时候不显示学历提升 <template v-if="type !== 'look'"> -->
      <template>
        <app-education-level
          ref="educationLevel1"
          :file-map="fileList"
          :type="type"
          :levelnum="1"
          :level-list="levelList"
        ></app-education-level>
        <app-education-level
          ref="educationLevel2"
          :file-map="fileList"
          :type="type"
          :levelnum="2"
          :level-list="levelList"
        ></app-education-level>
        <app-certificate
          :file-map="fileList"
          :type="type"
          ref="certificate"
        ></app-certificate>
      </template>
      <app-education
        :type="type"
        :level-list="levelList"
        v-if="isEducation"
        ref="education"
      ></app-education>
      <app-occupation
        :type="type"
        v-if="isOccupation"
        ref="occupation"
      ></app-occupation>
      <app-title :type="type" v-if="isTitle" ref="title"></app-title>
      <app-train :type="type" v-if="isTrain" ref="train"></app-train>
      <app-cost-information
        :type="type"
        :from="from"
        :fee-len="isEducation ? 4 : 2"
        ref="costInfo"
        :title="costTitle"
      ></app-cost-information>
      <app-refund-info
        v-if="isShowRefund"
        :type="type"
        ref="refundInfo"
      ></app-refund-info>
      <app-pay-voucher v-if="commitFlag" :file-map="fileList"></app-pay-voucher>
      <app-resolve-info
        v-if="isShowResolve"
        ref="resolveInfo"
      ></app-resolve-info>
      <el-row>
        <el-col style="display: flex; justify-content: center">
          <template v-if="type !== 'look'">
            <el-button
              :disabled="isSubmit"
              v-if="showSaveBtn"
              @click="handleValid('save')"
              type="primary"
              >保存</el-button
            >
            <el-button
              :disabled="isSubmit"
              @click="handleValid('submit')"
              type="primary"
              >提交</el-button
            >
          </template>
          <template v-else>
            <el-dialog
              title="打印单据"
              v-if="dialogVisible"
              :visible.sync="dialogVisible"
              width="80%"
            >
              <el-table
                :data="receiptData.fees"
                border
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  type="selection"
                  :selectable="isSelected"
                  width="55"
                >
                </el-table-column>
                <el-table-column prop="stage" label="期数"> </el-table-column>
                <el-table-column prop="amount" label="培训费">
                </el-table-column>
                <el-table-column prop="term" label="缴费日期">
                </el-table-column>
                <el-table-column
                  prop="flag"
                  :formatter="formatterFlag"
                  label="是否缴费"
                >
                </el-table-column>
                <el-table-column
                  prop="receiptStatus"
                  :formatter="formatterReceipt"
                  label="收据状态"
                >
                </el-table-column>
                <el-table-column prop="receiptNo" label="收据号">
                </el-table-column>
              </el-table>
              <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handlePrintReceipt"
                  >确 定</el-button
                >
              </span>
            </el-dialog>
            <el-button
              type="primary"
              v-if="isShowPrint"
              @click="dialogVisible = true"
              >打印单据</el-button
            >
            <el-button @click="handleBack" type="primary">返回</el-button>
          </template>
        </el-col>
      </el-row>
    </div>

    <script src="../../../js/jquery.js"></script>
    <script src="../../../js/common.js"></script>
    <script src="../../../js/vue.js"></script>
    <script src="../../../js/element.js"></script>
    <script src="./components/BaseInformation.js"></script>
    <script src="./components/EducationLevel.js"></script>
    <script src="./components/RefundInfo.js"></script>
    <script src="./components/Certificate.js"></script>
    <script src="./components/Education.js"></script>
    <script src="./components/Occupation.js"></script>
    <script src="./components/Title.js"></script>
    <script src="./components/Train.js"></script>
    <script src="./components/CostInformation.js"></script>
    <script src="./components/PayVoucher.js"></script>
    <script src="./components/ResolveInfo.js"></script>

    <script>
      const app = new Vue({
        el: "#app",
        created() {
          this.infoName = getQuery("trainType");
          this.showSaveBtn = !["3", "5"].includes(getQuery("commitFlag"));
        },
        mounted() {
          this.getPageTitle();
          this.getEducationOption();
          // 如果是通过操作进入当前页面，就调用获取的接口
          this.from = getQuery("from");
          this.isShowPrint = getQuery("action") === "print";
          this.pageNumber = Number(getQuery("pageNumber"));
          const commitFlagValue = ["0", "1"].includes(getQuery("commitFlag"));
          this.commitFlag = getQuery("commitFlag") ? !commitFlagValue : false;
          (this.type = getQuery("type")) &&
            this.$nextTick(() => {
              this.getStudentInfo();
            });
        },
        data: {
          commitFlag: false,
          pageNumber: 0,
          isSubmit: false,
          levelList: [],
          // 当前页面的名称
          infoName: "",
          id: "",
          genId: "",
          type: "",
          showSaveBtn: true,
          from: "",
          action: "",
          idNo: "",
          studyId: "",
          receiptData: [],
          isShowPrint: false,
          dialogVisible: false,
          multipleSelection: [],
          baseInfoMap: new Map([
            ["name", "name"],
            ["phoneNum", "phone"],
            ["idNo", "idNum"],
            ["nation", "nationality"],
            ["sex", "gender"],
            ["birthday", "birthday"],
            ["address", "address"],
            ["email", "email"],
            ["qqNumber", "qq"],
            ["workAdress", "work"],
          ]),
          educationLevel: new Map([
            ["major", "discipline"],
            ["educationName", "level"],
            ["studyMode", "path"],
            ["graduateSchool", "school"],
            ["graduateTime", "time"],
            ["certificateNumber", "cerNum"],
          ]),
          educationMap: new Map([
            ["studyMode", "pathLabel"],
            ["educationName", "levelLabel"],
            ["schoolName", "schoolLabel"],
            ["majorName", "discipline"],
            ["batch", "batch"],
          ]),
          occupationKeys: [
            "professionalTypes",
            "majorName",
            "batch",
            "applyExplain",
          ],
          titleKeys: [
            "professionalLevel",
            "professionalSeries",
            "majorName",
            "batch",
          ],
          trainKeys: [
            "applyProject",
            "examCourse",
            "classs",
            "applyAssist",
            "startDate",
            "endDate",
            "batch",
          ],
          feesMap: new Map([
            ["stage", "stage"],
            ["amount", "fee"],
            ["term", "feeDate"],
            ["flag", "isFee"],
            ["receiptStatus", "receipt"],
            ["receiptNo", "receiptNum"],
          ]),
          feeMap: new Map([
            ["otherFee", "otherFee"],
            ["paidinFee", "training"],
            ["explains", "description"],
            ["allFee", "total"],
            ["preferentialFee", "discount"],
            ["realPayFee", "paid"],
          ]),
          fileList: [],
        },
        computed: {
          isEducation() {
            return this.infoName === "education";
          },
          isOccupation() {
            return this.infoName === "occupation";
          },
          isTitle() {
            return this.infoName === "title";
          },
          isTrain() {
            return this.infoName === "train";
          },
          isShowResolve() {
            return this.from !== "bc";
          },
          isShowRefund() {
            return this.from === "refund";
          },
          isShowVoucher() {
            return;
          },
          costTitle() {
            const map = {
              education: "学历",
              occupation: "职业",
              title: "职称",
              train: "培训",
            };
            return map[this.infoName];
          },
        },
        methods: {
          isSelected(row) {
            return row.flag && row.receiptStatus == "0";
          },
          // 根据身份证号获取数据并填写
          getInfoByIdNoHandler(data) {
            this.fileList = data.studentCards;

            const {
              educationLevel1: educationLevelInfo,
              educationLevel2: educationLevelInfo2,
            } = this.getRefs("formData");

            for (item of this.educationLevel) {
              educationLevelInfo[item[1]] = data.student[item[0]];
              educationLevelInfo2[item[1]] = data.student[item[0] + "2"];
            }
          },
          handleSelectionChange(val) {
            this.multipleSelection = val;
          },
          formatterFlag(row) {
            return row.flag ? "是" : "否";
          },
          formatterReceipt(row) {
            if (row.receiptStatus == "0") {
              return "未打印";
            }
            if (row.receiptStatus == "1") {
              return "已打印";
            }
            if (row.receiptStatus == "2") {
              return "退款作废";
            }
            return "";
          },
          handlePrintReceipt() {
            if (!this.multipleSelection.length) {
              this.$message({
                message: "请勾选需要打印的缴费信息",
                type: "error",
              });
              return;
            }

            let typeName,
              courseType = "";

            const {
              studentEducation,
              studentOccupation,
              studentTitle,
              studentTrain,
            } = this.receiptData;
            if (studentEducation) {
              typeName = `${studentEducation.schoolName}`;
            }

            if (studentOccupation) {
              typeName = `${studentOccupation.majorName}`;
            }

            if (studentTitle) {
              typeName = `${studentTitle.majorName}`;
            }

            if (studentTrain) {
              courseType = studentTrain.classs;
              typeName = `${studentTrain.examCourse}`;
            }

            const data = {
              name: this.receiptData.student.name,
              phoneNum: this.receiptData.student.phoneNum,
              multipleSelection: this.multipleSelection,
              teacherName: decodeURI(getQuery("teacherName")),
              typeName,
              courseType,
            };
            localStorage.setItem("receiptData", JSON.stringify(data));
            let createDate = "";
            // window.location.href = './receipt-print.html';
            const selectedData = this.multipleSelection.map((item) => {
              const { createDate: date, ...data } = item;
              createDate = date && date.split(" ")[0];
              return data;
            });

            $.ajax({
              url: baseUrl + "studentInfo/receiptNoAndStatus",
              method: "Post",
              contentType: "application/json;charset=UTF-8",
              data: JSON.stringify(selectedData),
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              success: (data) => {
                if (data.code === 200) {
                  this.getStudentInfo();
                  this.$message({
                    message: "生成单据成功",
                    type: "success",
                  });

                  window.open(
                    `./receipt-print.html?no=${data.message}&createDate=${createDate}`
                  );
                }
                this.$message({
                  message: `${
                    this.action === "save" ? "保存成功" : "提交成功"
                  }`,
                  type: "success",
                });
              },
              error: (err, res, res1) => {
                this.$message({
                  message: err.responseJSON.message || "网络错误",
                  type: "error",
                });
              },
            });
          },
          handleBack() {
            var backPath = "";
            let name = getQuery("lookName");
            if (name === "jw") {
              backPath = "../trade/tradeSearch.html";
            } else if (name === "cw") {
              backPath = "../store/moneySearch.html";
            } else {
              backPath = "../hotel/studentSearch.html";
            }
            window.location.href = backPath + `?pageNumber=${this.pageNumber}`;
          },
          getPageTitle() {
            // 根据查询字符串info，来判断显示哪个报考信息
            const from = getQuery("from");
            const isEdit = getQuery("type") === "edit";
            switch (from) {
              case "student":
                localStorage.setItem(
                  "name",
                  `学生管理/学生信息查询/${isEdit ? "修改" : "查看"}`
                );
                break;
              case "jiaowu":
                localStorage.setItem("name", "教务管理/教务信息管理/修改");
                break;
              case "jiaofei":
                localStorage.setItem("name", "财务管理/缴费信息管理/修改");
                break;
              case "fenqi":
                localStorage.setItem("name", "学生管理/分期缴费信息查询/修改");
                break;
              case "tuanduiyeji":
                localStorage.setItem("name", "团队管理/业绩查询/查看");
                break;
            }
          },
          handleValid(flag) {
            this.action = flag;
            const errMap = {
              baseInfo: "基本信息未填写完成",
              educationLevel1: "第一学历未填写完成",
              educationLevel2: "第二学历未填写完成",
              certificate: "证书未填写完成",
              costInfo: "学历缴费信息未填写完成",
            };
            const infoMap = {
              education: {
                type: "education",
                msg: "学历报考信息未填写完成",
              },
              occupation: {
                type: "occupation",
                msg: "职业报考信息未填写完成",
              },
              title: {
                type: "title",
                msg: "职称报考信息未填写完成",
              },
              train: {
                type: "train",
                msg: "培训报考信息未填写完成",
              },
            };
            const formRef = this.getRefs("$refs");
            Object.keys(formRef).forEach((key) => {
              if (formRef[key] === undefined) {
                delete formRef[key];
              }
            });
            const formPList = Object.keys(formRef).map((item) => {
              return new Promise((resolve, reject) => {
                formRef[item] &&
                  formRef[item].form.validate((valid) => {
                    if (valid) {
                      resolve();
                    } else {
                      const msg =
                        this.infoName === item
                          ? infoMap[this.infoName].msg
                          : errMap[item];
                      reject(msg);
                    }
                  });
              });
            });

            Promise.all(formPList)
              .then((item) => {
                this.handleSave();
              })
              .catch((error) => {
                this.$message({
                  message: error,
                  type: "error",
                });
              });
          },
          getRefs(key = "") {
            const {
              baseInfo = {},
              educationLevel1 = {},
              educationLevel2 = {},
              certificate = {},
              costInfo = {},
              refundInfo = {},
              resolveInfo = {},
              education = {},
              occupation = {},
              title = {},
              train = {},
            } = this.$refs;

            return {
              baseInfo: baseInfo[key],
              educationLevel1: educationLevel1[key],
              educationLevel2: educationLevel2[key],
              certificate: certificate[key],
              costInfo: costInfo[key],
              refundInfo: refundInfo[key],
              resolveInfo: resolveInfo[key],
              education: education[key],
              occupation: occupation[key],
              title: title[key],
              train: train[key],
            };
          },
          handleSave() {
            const {
              baseInfo,
              educationLevel1,
              educationLevel2,
              certificate,
              costInfo,
              resolveInfo,
              education,
              occupation,
              title,
              train,
            } = this.getRefs("formData");

            const student = {
              id: this.id,
              pid: JSON.parse(localStorage.getItem("userInfo")).account.split(
                "-"
              )[1],
              // commitFlag: flag === "save" ? 0 : 1,
              name: baseInfo.name,
              phoneNum: baseInfo.phone,
              idNo: baseInfo.idNum,
              nation: baseInfo.nationality,
              sex: baseInfo.gender,
              birthday: baseInfo.birthday,
              address: baseInfo.address,
              email: baseInfo.email,
              qqNumber: baseInfo.qq,
              workAdress: baseInfo.work,
              // 学历1
              major: educationLevel1.discipline,
              educationName: educationLevel1.level,
              studyMode: educationLevel1.path,
              graduateSchool: educationLevel1.school,
              graduateTime: educationLevel1.time,
              certificateNumber: educationLevel1.cerNum,
              // 学历2
              major2: educationLevel2.discipline,
              educationName2: educationLevel2.level,
              studyMode2: educationLevel2.path,
              graduateSchool2: educationLevel2.school,
              graduateTime2: educationLevel2.time,
              certificateNumber2: educationLevel2.cerNum,
            };

            const mobile = JSON.parse(
              localStorage.getItem("userInfo")
            ).mobile.slice(7);
            const data = {
              student: [student],
            };
            if (education) {
              data.studentEducations = [
                {
                  studyMode: education.pathLabel,
                  educationName: education.levelLabel,
                  schoolName: education.schoolLabel,
                  majorName: education.discipline,
                  batch: education.batch,
                  flag: 1,
                  id: this.genId,
                },
              ];
            }
            if (occupation) {
              data.studentOccupations = [
                {
                  ...occupation,
                  flag: 1,
                  id: this.genId,
                },
              ];
            }
            if (title) {
              data.studentTitles = [
                {
                  ...title,
                  flag: 1,
                  id: this.genId,
                },
              ];
            }
            if (train) {
              train.examCourse = train.examCourse.toString();
              data.studentTrains = [
                {
                  ...train,
                  teacherId: JSON.parse(
                    localStorage.getItem("userInfo")
                  ).account.split("-")[1],
                  flag: 1,
                  id: this.genId,
                },
              ];
            }
            this.save(data);
          },
          save(data) {
            $.ajax({
              url: baseUrl + "studentInfo/updateStudentInfo",
              method: "Post",
              contentType: "application/json;charset=UTF-8",
              data: JSON.stringify({
                ...data,
              }),
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              success: (data) => {
                this.isSubmit = true;
                this.$message({
                  message: `${
                    this.action === "save" ? "保存成功" : "提交成功"
                  }`,
                  type: "success",
                });
                this.saveFee(data);
              },
              error: (err, res, res1) => {
                this.$message({
                  message: err.responseJSON.message || "网络错误",
                  type: "error",
                });
              },
            });
          },
          saveFee({ commitBoolean }) {
            const { costInfo } = this.getRefs("formData");
            // const costInfo = this.$refs.costInfo.formData;
            const fees = costInfo.fees.map((item) => {
              const data = {
                id: item.id,
                studentId: this.id,
                studyId: this.genId,
                teacherId: JSON.parse(
                  localStorage.getItem("userInfo")
                ).account.split("-")[1],
                commitBoolean,
                commitFlag: this.action === "save" ? 0 : 1,
                businessProgress: 0,
                trainType: this.infoName,
                // 期数
                stage: item.stage || "",
                // 缴费日期
                term: item.feeDate,
                // 缴费金额
                amount: item.fee == 0 ? 0 : item.fee || "",
                // 是否已缴费
                flag: item.isFee,
                // 收据状态
                receiptStatus: item.receipt,
                // 收据编号
                receiptNo: item.receiptNum,
                // 其他费用名称
                otherName: costInfo.otherName,
                // 报名费
                otherFee: costInfo.otherFee,
                // 培训费
                paidinFee: costInfo.training,
                // 说明
                explains: costInfo.description,
                // 总费用
                allFee: costInfo.total,
                // 优惠费用
                preferentialFee: costInfo.discount,
                // 实缴费用
                realPayFee: costInfo.paid,
              };
              return data;
            });

            $.ajax({
              url: baseUrl + "studentInfo/updateStudentFees",
              method: "post",
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              contentType: "application/json",
              data: JSON.stringify(fees),
              success: (data) => {
                this.saveFile();
              },
            });
          },
          saveFile() {
            const { certificate: certificateFromData } =
              this.getRefs("formData");
            const {
              baseInfo = null,
              educationLevel1 = null,
              educationLevel2 = null,
              certificate: certificateFileDic = null,
            } = this.getRefs("fileDic");

            const formData = new FormData();

            for (item of baseInfo) {
              formData.append("propertys", item[0]);
              formData.append("files", item[1]);
            }

            for (item of educationLevel1) {
              formData.append("propertys", item[0]);
              formData.append("files", item[1]);
            }

            for (item of educationLevel2) {
              formData.append("propertys", item[0]);
              formData.append("files", item[1]);
            }

            for (item of certificateFileDic) {
              formData.append("propertys", certificateFromData[item[0]]);
              formData.append("files", item[1]);
            }
            formData.append("studentId", this.id);
            formData.append("studyId", this.genId);
            formData.append("trainType", this.infoName);
            $.ajax({
              url: baseUrl + "studentInfo/uploadStuCertificate",
              method: "post",
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              data: formData,
              processData: false,
              contentType: false,
              mimeType: "multipart/form-data",
              success: function (data) {
                window.location.href = "../hotel/studentSearch.html";
              },
            });
          },
          getStudentInfo() {
            const trainType = getQuery("trainType");
            const idNo = getQuery("idNo");
            const studyId = getQuery("studyId");

            const {
              baseInfo,
              educationLevel1: educationLevelInfo,
              educationLevel2: educationLevelInfo2,
              certificate,
              costInfo,
              resolveInfo = {},
              refundInfo = {},
              education,
              occupation,
              title,
              train,
            } = this.getRefs("formData");

            $.ajax({
              url: baseUrl + "studentInfo/getStudentInfo",
              method: "get",
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              data: {
                idNo,
                trainType,
                studyId,
              },
              success: (data) => {
                this.id = data.student.id;
                this.receiptData = data;
                // baseInfo.id = data.student.id;
                for (item of this.baseInfoMap) {
                  baseInfo[item[1]] = data.student[item[0]];
                }

                for (item of this.educationLevel) {
                  educationLevelInfo[item[1]] = data.student[item[0]];
                  educationLevelInfo2[item[1]] = data.student[item[0] + "2"];
                }

                if (education) {
                  this.genId = data.studentEducation.id;
                  for (item of this.educationMap) {
                    education[item[1]] = data.studentEducation[item[0]];
                  }
                }

                if (occupation) {
                  this.genId = data.studentOccupation.id;
                  for (item of this.occupationKeys) {
                    occupation[item] = data.studentOccupation[item];
                  }
                }

                if (title) {
                  this.genId = data.studentTitle.id;
                  for (item of this.titleKeys) {
                    title[item] = data.studentTitle[item];
                  }
                }

                if (train) {
                  this.genId = data.studentTrain.id;
                  for (item of this.trainKeys) {
                    if (item === "examCourse") {
                      train[item] = data.studentTrain[item].split(",");
                    } else {
                      train[item] = data.studentTrain[item];
                    }
                  }
                }

                data.fees.map((feeItem, index) => {
                  refundInfo && (refundInfo.refundableFee = feeItem.realPayFee);
                  refundInfo && (refundInfo.deductFee = feeItem.deductFee);
                  refundInfo &&
                    (refundInfo.realRefundFee = feeItem.realRefundFee);
                  const performanceFlag = +feeItem.performanceFlag
                    ? +feeItem.performanceFlag
                    : "";
                  refundInfo && (refundInfo.performanceFlag = performanceFlag);
                  refundInfo && (refundInfo.refundInfo = feeItem.refundInfo);
                  refundInfo && (refundInfo.payee = feeItem.payee);

                  costInfo.otherName = feeItem.otherName;

                  for (item of this.feeMap) {
                    costInfo[item[1]] = feeItem[item[0]];
                  }

                  resolveInfo.denyReason = feeItem.denyReason;

                  for (feesItem of this.feesMap) {
                    costInfo.fees[index].id = feeItem.id;
                    costInfo.fees[index].studentId = feeItem.studentId;
                    costInfo.fees[index].studyId = feeItem.studyId;

                    if (["stage", "fee"].includes(feesItem[1])) {
                      costInfo.fees[index][feesItem[1]] =
                        feeItem[feesItem[0]] || undefined;
                    } else {
                      costInfo.fees[index][feesItem[1]] = feeItem[feesItem[0]];
                    }
                  }
                });
                this.fileList = data.studentCards;
              },
            });
          },
          getEducationOption() {
            $.ajax({
              url: baseUrl + "education/queryEducationList",
              async: false,
              method: "Post",
              headers: {
                Authorization: JSON.parse(localStorage.getItem("userInfo"))
                  .token,
              },
              success: (data) => {
                this.levelList = data;
              },
            });
          },
        },
      });
    </script>
  </body>
</html>
